<?php

namespace app\modules\admin\models\search;

use app\modules\admin\components\RouteRule;
use app\modules\admin\models\AuthRule;
use Yii;
use yii\base\Model;
use yii\data\ArrayDataProvider;

/**
 * AuthRuleSearch represents the model behind the search form about `app\modules\admin\models\AuthRule`.
 */
class AuthRuleSearch extends Model
{
	/**
	 * @var string name of the rule
	 */
	public $name;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'safe'],
        ];
    }

    public function attributeLabels()
	{
		return [
			'name' => '规则名称'
		];
	}

	/**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return \yii\data\ActiveDataProvider|ArrayDataProvider
     */
    public function search($params)
    {
		$rules = Yii::$app->authManager->getRules();
		$models = [];
		$include = !($this->load($params) && $this->validate() && trim($this->name) !== '');
		foreach ($rules as $name=>$item) {
			if($name != RouteRule::RULE_NAME && ($include || stripos($item->name, $this->name) !== false)) {
				$models[$name] = new AuthRule($item);
			}
		}
		return new ArrayDataProvider([
			'allModels' => $models,
		]);
    }
}
